from flask import Blueprint
from flask import request
from flask import jsonify
import os, json, re

from common.libs.Helper import SaveImage
from common.libs.UrlManager import UrlManager
from common.models.Image import Image
from application import app

route_upload = Blueprint('upload', __name__)

@route_upload.route('/pic',methods=['GET','POST'])
def upload_pic():
    """
    上传封面图片
    :return:
    """
    upfile = request.files.get('pic')
    callback_target = 'window.parent.upload'
    if not upfile:
        return "<script type='text/javascript'>{0}.error('{1}')</script>".format(callback_target, "上传失败")
    # 上传图片保存
    res = SaveImage(upfile)
    if res['code'] == -1:
        return "<script type='text/javascript'>{0}.error('{1}')</script>".format(callback_target, "上传失败:" + res['msg'])
    return "<script type='text/javascript'>{0}.success('{1}')</script>".format(callback_target, res['data']['file_key'])

@route_upload.route('/ueditor', methods=['GET', 'POST'])
def upload():
    """
    ueditor上传图片功能
    :return:
    """
    action = request.args.get('action')
    if action == 'config':
        return UploadConfig()

    if action == 'uploadimage':
        return UploadImage()

    if action == 'listimage':
        return ListImage()

def UploadConfig():
    """
      ueditor上传图片后台配置
    :return:
    """
    upload_config_path = os.path.join(
        app.root_path, 'web/static/plugins/ueditor/upload_config.json'
    )
    with open(upload_config_path, encoding='utf-8') as fp:
        try:
            # 删除 /* */之间的注释
            CONFIG = json.loads(
                re.sub(r'/\*.*\*/', '', fp.read())
            )
        except Exception as error:
            print(error)
            CONFIG = {}

    return jsonify(CONFIG)

def UploadImage():
    """
     ueditor上传图片保存到后台
    :return:
    """
    result = {"state": "SUCCESS", "url": "", "title": "", "original": ""}
    upfile = request.files.get('upfile')

    if not upfile:
        result['state'] = '上传失败！'
        return jsonify(result)
    # 上传图片保存
    res = SaveImage(upfile)

    if res['code'] == -1:
        result['state'] = '上传失败:' + res['msg']
        return jsonify(result)

    result['url'] = UrlManager.buildImageUrl(res['data']['file_key'])
    return jsonify(result)

def ListImage():
    """
     ueditor上传图片前台展示，并分页
    :return:
    """
    result = {"state": "SUCCESS", "list": [], "start": 0, "total": 0}
    page = request.args.get('start', type=int, default=0)
    page_size = request.args.get('size', type=int, default=20)

    query = Image.query
    page_offset = page * page_size

    image_list = query.order_by(Image.id.desc()).offset(page_offset).limit(page_size).all()

    if image_list:
        for image in image_list:
            result['list'].append({
                'url': UrlManager.buildImageUrl(image.file_key)
            })

    result['start'] = page + 1
    result['total'] = len(image_list)

    return jsonify(result)
